﻿using UnityEngine;
using System.Collections;

public class TimerManager : MonoBehaviour {
	
	protected bool paused = false;
	
	public void StartTimer(IEnumerator task, OnVoidHandler onFinished)
	{
		this.StartCoroutine(AnonymousCoroutine(task,onFinished));
	}

	public void StartTimer(Timer task)
	{
		this.StartCoroutine(CoroutineWrapper(task));
	}

	public bool Pause
	{
		get{return paused;}
		set{paused = value;}
	}

	IEnumerator AnonymousCoroutine(IEnumerator coroutine,OnVoidHandler finishHandler = null)
	{
		IEnumerator e = coroutine;
		while(true)
		{
			if(Pause)
				yield return null;
			if(e != null && e.MoveNext())
				yield return e.Current;
			else
				break;
		}
		OnVoidHandler handler = finishHandler;
		if(handler!=null)
			handler();
	}
	
	IEnumerator CoroutineWrapper(Timer t)
	{
		t.Running = true;
		IEnumerator e = t.Coroutine();
		while(t!=null&&t.Running)
		{
			if(Pause)
				yield return null;
			if(t.Pause)
				yield return null;
			if(e != null && e.MoveNext())
				yield return e.Current;
			t.Running = false;
		}
		OnVoidHandler<bool> handler = t.OnFinished;
		if(handler!=null)
			handler(t.Running);
	}
}

public class Timer{


	protected IEnumerator coroutine=null;
	protected bool running;
	protected bool paused;
	protected bool stopped;
	protected OnVoidHandler<bool> finishHandler=null;


	public static Timer Create(IEnumerator i, OnVoidHandler<bool> OnFinished)
	{
		Timer t = new Timer(i, OnFinished);
		return t;
	}

	protected Timer(IEnumerator i, OnVoidHandler<bool> onFinished)
	{
		coroutine = i;
		finishHandler = onFinished;
		running = false;
		paused = false;
		stopped = false;
	}

	public IEnumerator Coroutine()
	{
		return coroutine;
	}

	public bool Running
	{
		get{ return running;}
		set{ running = value;}
	}

	public bool Pause {
		get {
			return paused;
		}
		set {
			paused = value;
		}
	}

	public void Stop()
	{
		running = false;
	}
	

	public OnVoidHandler<bool> OnFinished
	{
		get{return finishHandler;}
		set{finishHandler = value;}
	}	
}
